package com.heima.comment.service.impl;
import java.math.BigDecimal;
import java.util.Date;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dto.CommentRepayDto;
import com.heima.model.comment.dto.CommentRepayLikeDto;
import com.heima.model.comment.dto.CommentRepaySaveDto;
import com.heima.model.comment.pojo.ApComment;
import com.heima.model.comment.pojo.ApCommentRepay;
import com.heima.model.comment.pojo.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    UserFeign userFeign;

    //根据评论ID加载回复列表
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {

        //检测 参数  (size
        if (dto.getSize()==null||dto.getSize()<0){
            dto.setSize(10);
        }

        //根据评论id=? and 创建条件  <最小时间   limit  size  按照时间顺序降序
        //用户不一定要登录

        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate())).limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);

        //判断用户是否登录   没登录直接返回数据
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null||apCommentRepays==null||apCommentRepays.size()==0){
            return ResponseResult.okResult(apCommentRepays);
        }
        //如果登录了,判断哪些回复  登录用户点过赞
        //抽取当前页所有回复的id
        List<String> repayIds = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());

        //根据回复的ids 和当前  登录userId  查询哪些评论  回复  点过赞
        //得到点赞过的数据
        Query query1 = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").in(repayIds));//      在查询到的评论列表中查询喜欢的
        List<ApCommentRepayLike> repayLiked = mongoTemplate.find(query1, ApCommentRepayLike.class);

        List<String> repayLikedIds = repayLiked.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());

        //循环遍历评论回复列表   筛选出喜欢的   将每一个回复  封装成vo  如果点过赞   将vo中的operation  设置为0
        List<ApCommentRepayVo> commentRepayVos = apCommentRepays.stream().map(apCommentRepay -> {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVo);
            if (repayLikedIds.contains(apCommentRepay.getId())) {
                apCommentRepayVo.setOperation((short) 0);
            }
            return apCommentRepayVo;
        }).collect(Collectors.toList());

        return ResponseResult.okResult(commentRepayVos);
    }

    //保存评论回复,在回复列表中新增评论
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1.检查参数

        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

         user = userFeign.findUserById(Long.valueOf(user.getId()));
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"获取登录用户失败");
        }
        //2.根据评论id查询评论信息
        //数据存储到mongodb中
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"评论数据不存在");
        }
        //3.使用阿里云文本内容检查

        //调用阿里云进行评论内容文本检测
        //引入阿里云依赖
        //注入GreenTextScan
        //扫描文本  根据结果进行处理
        Boolean isTextScan = handleTextScan(dto.getContent());
        if (!isTextScan) return null;
        log.info("当前处理的评论,通过了阿里云的文本审核");

        //4.保存回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.insert(apCommentRepay);//插入一条新数据

        //5.将对应的评论回复数量+1
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult();
    }


    @Autowired
    GreenTextScan greenTextScan;

    private Boolean handleTextScan(String content) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            if ("review".equals(suggestion)) {
                flag = false;
                log.info("内容中包含不确定因素,请人工审核");
            }
            if ("block".equals(suggestion)) {
                flag = false;
                log.info("文本中包含敏感词汇");
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            log.info("阿里云审核失败,转为人工");
        }
        return flag;
    }

    //点赞   评论回复
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //检查参数   是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"需要登录");
        }
        //根据回复ID   查询回复数据
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"评论回复数据不存在");
        }
        //查看是否点赞   查询点赞集合     如果有点赞数据   并且  operation为0  说明点过赞   重复点赞问题
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (apCommentRepayLike!=null&&dto.getOperation().intValue()==0){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
        }
        //根据方式进行处理
        //1  如果点赞操作   评论回复  点赞数量+1  保存点赞信息

        if (dto.getOperation().intValue()==0){

             apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short)0);
            mongoTemplate.insert(apCommentRepayLike);


            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);
        }else {
            apCommentRepay.setLikes(apCommentRepay.getLikes()<1?0:apCommentRepay.getLikes()-1);
            mongoTemplate.save(apCommentRepay);
            mongoTemplate.remove(query,ApCommentRepayLike.class);
        }
        Map map = new HashMap<>();
        map.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(map);


        //2.  如果取消点赞   评论回复的  点赞数量-1  删除点赞信息

        //返回结果   携带最新的点赞数量   likes
    }
}
